package cn.mw.cmdb.service.handler.monitorData;

import cn.mw.cmdb.entity.ItemDropInfo;
import cn.mw.cmdb.enums.ChartTypeEnum;
import cn.mw.cmdb.param.ItemNameParam;
import cn.mw.cmdb.param.MwBaseMonitorDataResult;
import cn.mw.cmdb.param.MwItemHistoryResult;
import cn.mw.cmdb.param.QueryItemHistoryParam;
import cn.mw.cmdb.param.zabbixResult.MWItemHistoryDTO;
import cn.mw.cmdb.param.zabbixResult.MwMonitorHistoryParam;
import cn.mw.cmdb.processor.MonitorParamContext;
import cn.mw.cmdb.processor.MonitorProcessor;
import cn.mw.cmdb.service.MwMonitorProcessorConvert;
import cn.mw.cmdb.service.impl.CmdbServiceManage;
import cn.mw.main.api.common.ZabbixDubboService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.enums.ChartTypeEnum.getChartEnumByName;
import static cn.mw.cmdb.service.handler.monitorData.MonitorHandlerUtils.*;

/**
 * 历史数据查询
 */
@Slf4j
public class MonitorHistoryHandler implements HistoryHandlerProcessor<MwMonitorHistoryParam> {

    private CmdbServiceManage cmdbServiceManage;
    private ZabbixDubboService zabbixDubboService;

    private List<String> mergeItemList = Arrays.asList("MEMORY_UTILIZATION");

    public MonitorHistoryHandler(CmdbServiceManage cmdbServiceManage, ZabbixDubboService zabbixDubboService) {
        this.cmdbServiceManage = cmdbServiceManage;
        this.zabbixDubboService = zabbixDubboService;
    }

    public MonitorHistoryHandler() {
    }

    @Override
    public Object genMonitorData(MwMonitorHistoryParam param) {
        MwBaseMonitorDataResult baseData = new MwBaseMonitorDataResult();
        QueryItemHistoryParam itemHistoryParam = historyParamConvert(param);
        Map<String, ItemDropInfo> itemInfoByMap = new HashMap<>();
        ChartTypeEnum chartTypeEnum = getChartEnumByName(param.getChartType());

        MwMonitorProcessorConvert processorConvert = new MwMonitorProcessorConvert(cmdbServiceManage, zabbixDubboService);
        //获取查询监控参数context
        MonitorParamContext contextParam = processorConvert.getContextParam(itemHistoryParam, null);
        //获取查询监控processor
        MonitorProcessor processor = processorConvert.getMonitorProcessor(param);
        //具先监控参数context中的MwInstanceZabbixParam参数
        contextParam.setQueryMonitorParam(param);
        List<MWItemHistoryDTO> monitorHistoryData = new ArrayList<>();
        List<ItemNameParam> names = new ArrayList<>();
        Set<String> nameSet = new HashSet<>();
        Map<String, ItemNameParam> collect = new HashMap<>();
        long time1 = System.currentTimeMillis();
        long time2 = 0;
        if (processor != null) {
            contextParam.setParam(param);
            names = processor.getNames(contextParam);
            if(names != null ){
                nameSet = names.stream().map(s -> s.getDevName()).collect(Collectors.toSet());
                if(CollectionUtils.isNotEmpty(param.getInterfaceDrops())){
                    collect = names.stream().filter(s->param.getInterfaceDrops().contains(s.getDevName())).collect(Collectors.toMap(s -> s.getItemId(), s -> s, (o1, o2) -> o1));
                }else{
                    collect = names.stream().collect(Collectors.toMap(s -> s.getItemId(), s -> s, (o1, o2) -> o1));
                }
            }
            time2 = System.currentTimeMillis();
            if(collect!=null && collect.size()>0){
                itemHistoryParam.setItemIds(new ArrayList<>(collect.keySet()));
            }
            contextParam.setParam(itemHistoryParam);
            monitorHistoryData = processor.getMonitorHistoryData(contextParam);
        }
        long time3 = System.currentTimeMillis();
        log.info("getMonitorHistory::getNames耗时:"+(time2-time1)+"ms;getMonitorHistoryData耗时:"+(time3-time2)+"ms");
        List<String> sortNames = new ArrayList<>();
        Map<String, ItemDropInfo> stringItemDropInfoMap = new HashMap<>();
                switch (chartTypeEnum) {
            case rateLine://占用率组件，监控项设备名称合并处理
                itemInfoByMap = itemHistoryParam.getItemInfoByItemName();
                sortNames = new ArrayList<>();
                stringItemDropInfoMap = setItemInfoToDevName(itemInfoByMap, collect);
                break;
            default://其他组件，监控项设备名称拆分处理（DevName）
                itemInfoByMap = itemHistoryParam.getItemInfoByItemId();
                List<String> nameList = new ArrayList<>(nameSet);
                sortNames = nameList.stream().sorted().collect(Collectors.toList());
                stringItemDropInfoMap = setItemInfoToDisDevName(itemInfoByMap, collect);
        }
        List<MwItemHistoryResult> historyResultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(monitorHistoryData)){
            historyResultList = monitorConvertDataHandle(monitorHistoryData, param, stringItemDropInfoMap);
        }
        baseData.setInterfaceDrops(sortNames);
        baseData.setItemTotalInfoList(historyResultList);
        return baseData;
    }

}
